import { ref, reactive } from 'vue'
import { getUserDataAPI,updateUserDataAPI } from '@/api/user'
import storage from '@/utils/storage'
import { uploadFileApi } from "@/api";

export function useUserData()  {

    const userData = ref({})
    const popupRef = ref(null)
    const updateParams  = reactive({
        type: 'input',
        label: '',
        key: ''
    })
    const updateFormData = reactive({
        id: '',
        name: '',
        sex: '',
        phone: ''
    })
    function getUserData() {
        const { username } = storage.get('userInfo')
        return getUserDataAPI(username).then(res => {
            userData.value = res
            storage.set('userInfo', res)
            for (const key in updateFormData) {
                updateFormData[key] = res[key]
            }
        })
    }
    const afterRead = async event => {
        let file = event.file;
        try {
            const avatar = await uploadFileApi(file.url, 'avatar')
            await updateUserData({ id: userData.value?.id, avatar })
            uni.showToast({title: '头像上传成功', icon: 'none'})
        }catch (e) {}
    }

    const updateUserData = async data => {
        try {
            await updateUserDataAPI(data)
            await getUserData()
        }catch (e) {}
    }
    const handleToUpdate = (label, key, type = '') => {
        updateParams.label = label
        updateParams.key = key
        updateParams.type = type
        popupRef.value?.open()
    }
    async function updateUserInfo () {
        if(updateFormData[updateParams.key] === '' || updateFormData[updateParams.key] === null) {
            return uni.showToast({ title: '请输入修改内容', icon: 'none'})
        }
        await updateUserData(updateFormData)
        popupRef.value?.close()
    }
    return {
        userData,
        getUserData,
        afterRead,
        popupRef,
        handleToUpdate,
        updateParams,
        updateFormData,
        updateUserInfo
    }
}
